package com.dkd.day202511;

import com.dkd.day20250614.ListNode;

public class Solution1 {
    //给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(1);
        System.out.println(isPalindrome(head));
    }

    public static boolean isPalindrome(ListNode head) {
        //低效
        //回文链表，不是环
        //思路，反转，然后同步前进
        if (head == null || head.next == null)  return true;
        //复制head
        ListNode headCopy = new ListNode(head.val);
        ListNode cur = head;
        ListNode curCopy = headCopy;
        while (cur.next != null) {
            curCopy.next = new ListNode(cur.next.val);
            curCopy = curCopy.next;
            cur = cur.next;
        }
        ListNode reverse = reverse(headCopy);
        while (reverse != null) {
            if (head.val != reverse.val) return false;
            head = head.next;
            reverse = reverse.next;
        }
        return true;
    }

    public static ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode prev = null;//设置虚拟头节点
        ListNode temp;
        while (head!= null) {
            temp = head.next;//存储头节点的下一节点
            head.next = prev;//头节点链接前驱节点
            prev = head;//前驱节点变原头节点
            head = temp;//头节点变下一节点
        }
        return prev;

    }

    //优解，快慢指针找一半
    public boolean isPalindromeTrue(ListNode head) {
        if (head == null) {
            return true;
        }

        // 找到前半部分链表的尾节点并反转后半部分链表
        ListNode firstHalfEnd = endOfFirstHalf(head);
        ListNode secondHalfStart = reverseList(firstHalfEnd.next);

        // 判断是否回文
        ListNode p1 = head;
        ListNode p2 = secondHalfStart;
        boolean result = true;
        while (result && p2 != null) {
            if (p1.val != p2.val) {
                result = false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }

        // 还原链表并返回结果
        firstHalfEnd.next = reverseList(secondHalfStart);
        return result;
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    private ListNode endOfFirstHalf(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }


}
